<script setup>
import { ref } from 'vue'
import {
  ScenicSpotUpdateService,
  ScenicSpotAddService
} from '@/api/scenicSpots'
import { Plus } from '@element-plus/icons-vue'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import ScenicSpotSelect from './ScenicSpotSelect.vue'
const defaultModel = ref({
  id: null,
  scenicAreaId: null,
  scenicSpotImages: '',
  scenicSpotInfo: '',
  scenicSpotName: ''
})
const formRef = ref(null)
const formModel = ref({
  ...defaultModel.value
})
const imgUrl = ref()
const visibleDrawer = ref(false)
const editorRef = ref()
//图片
const onSelectFile = (uploadFile) => {
  if (uploadFile) {
    imgUrl.value = URL.createObjectURL(uploadFile.raw) // 预览图片
    formModel.value.scenicSpotImages = uploadFile.raw
  }
}
const fileList = ref([])
const emit = defineEmits(['success'])

const onPublish = async () => {
  if (!formModel.value.scenicSpotName) {
    ElMessage.error('景点名称不能为空')
    return
  }
  if (!formModel.value.scenicSpotInfo) {
    ElMessage.error('请输入景点介绍')
    return
  }
  if (formModel.value.scenicSpotImages.length === 0) {
    ElMessage.error('请上传景区图片')
    return
  }
  if (formModel.value.scenicAreaId === null) {
    ElMessage.error('请选择景区名称')
    return
  }

  const fd = new FormData()
  const textContent = formModel.value.scenicSpotInfo.replace(/<[^>]+>/g, '')

  fd.append('scenicSpotInfo', textContent)
  fd.append('scenicSpotName', formModel.value.scenicSpotName)
  // fd.append('scenicSpotImages', formModel.value.scenicSpotImages)
  // for (let i = 0; i < formModel.value.scenicSpotImages.length; i++) {
  //   fd.append('scenicSpotImages', formModel.value.scenicSpotImages[i])
  // }

  fd.append('scenicSpotImages', formModel.value.scenicSpotImages)

  fd.append('scenicAreaId', parseInt(formModel.value.scenicAreaId))
  const isEdit = formModel.value.id !== undefined && formModel.value.id !== null
  if (isEdit) {
    console.log('isEdit', isEdit)
    fd.append('id', parseInt(formModel.value.id))
  }

  console.log('Form data being sent:', Array.from(fd.entries())) // 打印FormData内容
  try {
    let res
    if (isEdit) {
      console.log('isEdit', isEdit)
      res = await ScenicSpotUpdateService(fd)
    } else {
      res = await ScenicSpotAddService(fd)
    }
    console.log('Operation response:', res)

    if (res && res.code === 401) {
      ElMessage.error(res.message || '操作失败')
    } else {
      ElMessage.success(isEdit ? '编辑成功' : '添加成功')
      visibleDrawer.value = false
      emit('success')
    }
  } catch (error) {
    console.error('Form submission error:', error)
    ElMessage.error('表单提交失败，请检查输入')
  }
}

const open = async (row) => {
  visibleDrawer.value = true
  console.log('row', row)
  if (row.id) {
    formModel.value.scenicSpotImages = row.scenicSpotImages
    imgUrl.value = row.scenicSpotImages
    formModel.value = { ...row }
  } else {
    formModel.value = { ...defaultModel }
    formModel.value.scenicSpotImages = []
    editorRef.value.setHTML('')
    imgUrl.value = ''
  }
}
defineExpose({ open })
</script>

<template>
  <el-drawer
    v-model="visibleDrawer"
    :title="formModel.id ? '编辑景点' : '添加景点'"
    direction="rtl"
    size="50%"
  >
    <!-- 发表表单 -->
    <el-form :model="formModel" ref="formRef" label-width="100px">
      <el-form-item label="景点名称" prop="scenicSpotName">
        <el-input
          v-model="formModel.scenicSpotName"
          placeholder="请输入景点名称"
        ></el-input>
      </el-form-item>

      <el-form-item label="景点图片" prop="scenicSpotImages">
        <el-upload
          class="avatar-uploader"
          :show-file-list="true"
          :auto-upload="false"
          :on-change="onSelectFile"
          :file-list="fileList"
        >
          <img v-if="imgUrl" :src="imgUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="景区名称">
        <scenic-spot-select
          v-model="formModel.scenicAreaId"
        ></scenic-spot-select>
      </el-form-item>
      <el-form-item label="景点介绍">
        <div class="editor">
          <quill-editor
            theme="snow"
            v-model:content="formModel.scenicSpotInfo"
            contentType="html"
            ref="editorRef"
          >
          </quill-editor>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button @click="onPublish" type="primary">发布</el-button>
        <el-button @click="visibleDrawer = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>
<style lang="scss" scoped>
.avatar-uploader {
  :deep() {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
    .el-upload:hover {
      border-color: var(--el-color-primary);
    }
    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}

.editor {
  width: 100%;
  :deep(.ql-editor) {
    min-height: 200px;
  }
}
.el-icon--upload {
  margin-left: 50px;
}
.mapInput {
  width: 680px;
  margin-right: 10px;
}
</style>
